<script setup lang="ts">
import { getHomeBannerApi, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import { useGuessList } from '@/composables'

const bannerData = ref<BannerItem[]>([]) // 轮播图数据列表
const categoryData = ref<CategoryItem[]>([]) // 分类列表
const hotPanelData = ref<HotItem[]>([]) // 热门推荐列表
const status = ref(false) // 下拉刷新的状态
const isLoading = ref(false)
const getHomeBannerData = async () => {
  const res = await getHomeBannerApi()
  bannerData.value = res.result
}
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryData.value = res.result
}
const getHomeHotPanelData = async () => {
  const res = await getHomeHotAPI()
  hotPanelData.value = res.result
}

const { guessRef, onScrolltolower } = useGuessList()

// 下拉刷新触发
const onRefresherrefresh = async () => {
  status.value = true
  guessRef.value?.resetData() //重置数据
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotPanelData(),
    guessRef.value?.getHomeGoodsGuessLikeData(),
  ])
  status.value = false
}
// 页面加载时 触发，钩子
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotPanelData()])
  isLoading.value = false
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <scroll-view
    class="scrollView"
    scroll-y
    @scrolltolower="onScrolltolower"
    :refresher-triggered="status"
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 自定义轮播图 -->
      <XtxSwiper :list="bannerData" />
      <!-- 分类导航 -->
      <CategoryPanel :list="categoryData" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotPanelData" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scrollView {
  flex: 1;
}
</style>
